<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path;
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
<title>云校通-教师-<c:choose><c:when test="${examKey == null }">新增课程</c:when><c:otherwise>课程编辑</c:otherwise></c:choose></title>
<jsp:include page="/WEB-INF/page/common/_header.jsp"></jsp:include>
<script src="<%=basePath %>/js/picker.js"></script>
<script src="<%=basePath %>/js/select.js"></script>
<body ontouchstart class="js-jf">
	<div class="weui_tab tab-bottom">
		<div class="weui-header bg-blue"> 
	  		<div class="weui-header-left"> <a onclick="back()" href="javascript:;" class="icon icon-109 f-white">返回</a></div>
	    	<h1 class="weui-header-title">
	    		<c:choose>
	    			<c:when test="${courseId == null }">新增课程</c:when>
	    			<c:otherwise>课程编辑</c:otherwise>
	    		</c:choose>
	    	</h1>
	    	<div class="weui-header-right"> 
	    		<c:if test="${courseId != null }">
	    			<a id="action" href="javascript:;" class="f-white">修改</a >
	    		</c:if>
	    	</div>
	    </div>
		<div class="weui_tab_bd">
		    <div class="weui_panel_bd" style="margin-bottom: 55px;">
				<div class="weui_cells weui_cells_form mt0">
					<div class="weui_cell">
			          	<div class="weui_cell_hd">
			          		<label class="weui_label">课程名称</label>
			          	</div>
		         		<div class="weui_cell_bd weui_cell_primary no_icon">
							<input id="courseName" type="text" class="weui_input tr" placeholder="请输入课程名称" readonly/>
		      			</div>
		    		</div>
			     </div>
			     <div class="weui_cells weui_cells_form mt0">
			     	<div class="weui_cell">
	          			<div class="weui_cell_hd">
	            			<label class="weui_label label3">课程详情</label>
	          			</div>
		      		</div>
		            <div class="weui_cell">
		                <div class="weui_cell_bd weui_cell_primary">
		                    <textarea id="courseDesc" class="weui_textarea" placeholder="请输入通知内容……" rows="5" readonly></textarea>
		                </div>
		            </div>
		            <div class="weui_uploader">
	                    <div class="weui_uploader_bd">
	                         <ul class="weui_uploader_files img-click" id="img1">
	                         </ul>
	                      <div class="weui_uploader_input_wrp hide" id="filePicker" style="border-radius: 5px; margin: 5px 15px;">
	                      	<input class="weui_uploader_input" type="file" accept="image/jpg,image/jpeg,image/png,image/gif" id="imgid"/>
	                      </div>
	                    </div>
	                </div>
		         </div>
		         <div class="weui_cells weui_cells_form mt0">
	 				<div class="weui_cell">
			            <div class="weui_cell_hd">
			              <label class="weui_label label3">任课老师</label>
			            </div>
			            <div class="weui_cell_bd weui_cell_primary hide" id="teacherConf">
	  						<input type="text" class="weui_input weui_input-select main1" placeholder="请选择任课老师" disabled>
	            		</div>
	 	      		</div>
	        		<div class="pfy">
						<ul class="pfy_show" id="classTeachers">
						</ul>
						<input type="hidden" id="classTeacher"/>
						<input type="hidden" id="classTeacherIds"/>
	      			</div>
				 </div>
			     <div class="weui_cells weui_cells_form mt0" id="regExamGrade">
			      	<div class="weui_cell">
	          			<div class="weui_cell_hd">
	            			<label class="weui_label label3">上课地点</label>
	          			</div>
	          			<div class="weui_cell_bd weui_cell_primary">
							<input class="weui_input right" type="text" id='classAddr' placeholder="请输入上课地点" readonly/>
		          		</div>
		      		</div>
		      		<div class="weui_cell">
	          			<div class="weui_cell_hd">
	            			<label class="weui_label label3">备用地点</label>
	          			</div>
	          			<div class="weui_cell_bd weui_cell_primary">
							<input class="weui_input right" type="text" id='rainAddr' placeholder="请输入备用地点" readonly/>
		          		</div>
		      		</div>
		      		<div class="weui_cell">
	          			<div class="weui_cell_hd">
	            			<label class="weui_label label3">课程限制人数</label>
	          			</div>
	          			<div class="weui_cell_bd weui_cell_primary">
							<input id="limitNum" class="weui_input tr" type="number" pattern="[0-9]*" placeholder="请输入课程限制人数" readonly>
		          		</div>
		      		</div>
			     </div>
			     <div class="weui_cells weui_cells_form mt0">
			     	<div class="weui_cell">
			            <div class="weui_cell_hd">
			              <label class="weui_label label3">授课对象</label>
			            </div>
			            <div class="weui_cell_bd weui_cell_primary" id="teachingObjectConf">
	  						<input id="teachingObject" type="text" class="weui_input tr" placeholder="请选择授课对象" readonly>
	            		</div>
	 	      		</div>
	        		<div class="pfy">
						<ul class="pfy_show" id="teachingObjects">
						</ul>
	      			</div>
			     </div>
			     <div class="weui_cells weui_cells_form mt0">
			     	<div class="weui_cell">
			            <div class="weui_cell_hd">
			              <label class="weui_label label3">巡查人</label>
			            </div>
			            <div class="weui_cell_bd weui_cell_primary hide" id="watchTeacherConf">
	  						<input type="text" class="weui_input weui_input-select main1" placeholder="请选择巡查人" disabled>
	            		</div>
	 	      		</div>
	        		<div class="pfy">
						<ul class="pfy_show" id="watchTeachers">
						</ul>
						<input type="hidden" id="watchTeacher"/>
						<input type="hidden" id="watchTeacherIds"/>
	      			</div>
			     </div>
			     <c:if test="${courseId == null }">
				     <div class="weui_btn_area">
				        <a href="javascript:" class="weui_btn bg-blue" id="examSubmit">确认提交</a>
				     </div>
				 </c:if>
			</div>
		</div>
	</div>
	
	<!-- 这里的div的class后面加上 display可以显示点击效果 -->
	<div class="hide_bd"></div>
	<div class="hb_choose type1">
		<h1>请选择对象</h1>   
		<div class="searchbar_wrap"></div>
		<div class="name_show">
			<ul></ul>
		</div>
		<div class="name_show_box">
			<ul>
			</ul>
		</div>
		<input type="hidden" id="type"/>
		<div class="bg_white last_li">
			<strong><b class="cancel">取消</b></strong>
			<strong><b class="bg-blue f-white" id="sure">确认</b></strong>
	    </div>
	</div>
</body>
<jsp:include page="/WEB-INF/page/common/_footer.jsp"></jsp:include>
<script>
	var courseId = emptyToNull("${courseId}");
    $(function(){
    	$('.searchbar_wrap').searchBar({
	        cancelText:"取消",
	        searchText:'请输入教师名称',
	        onfocus: function (value) {
	           $('.name_show_box').show();
	        },
	        onblur:function(value) {
	        		
	        },
	        input: function(value) {
	        	queryItem(value);
	        },
	        onsubmit:function(value){
	        	queryItem(value);
	        },
	        oncancel:function(){
	        	$('.name_show_box ul').html('');
	        	$('.name_show_box').hide();
	        },
	        onclear:function(){
	        	$('.name_show_box ul').html('');
	        	$('.name_show_box').hide();
	        }
	    });
	   	$('#gradeConf').click(function(){
	   		loadMaskGrade();
	 		$('.hide_bd').attr("style", "display: block");
	 		$('.type2').show();
	 	});
	   	$('#teacherConf').click(function(){
	   		$("#type").val("classTeachers");
	   		loadMaskTeacher('classTeachers');
	 		$('.hide_bd').attr("style", "display: block");
	 		$('.type1').show();
	 	});
	   	$('#watchTeacherConf').click(function() {
	   		$("#type").val("watchTeachers");
	   		loadMaskTeacher("watchTeachers");
	 		$('.hide_bd').attr("style", "display: block");
	 		$('.type1').show();
	   	});
   	 	$("#action").click(function() {
   	 		var text = $(this).html();
   	 		if(text == '修改') {
   	 			initPage();
   	 			$(this).html("保存");
   	 		}else if(text == "保存") {
   	 			examSubmit();
   	 		}
   	 	});
	   	
	   	$('.last_li .cancel').click(function(){
    		$('.hide_bd').attr("style", "display: none");
    		$('.type2').hide();
    		$('.type1').hide();
    	});
	   	$("#examSubmit").click(function() {
	   		examSubmit();
	   	})
	   	if(courseId == null) {
	   		initPage();
	   	}
	   	function listDel(thiz){
	   		$(thiz).remove();
	   	}
	   	$(".type1 #sure").click(function() {
	   		var teachers = "";
	   		var teacherIds = "";
	   		var length = $(".name_show").find("li").length;
	   		$(".name_show").find("li").each(function(i, v) {
	   			teacherIds += $(v).attr("data-id") + ((i+1) < length ? "," : "");
	   			teachers += $(v).attr("data-name") + ((i+1) < length ? "," : "");
	   		})
	   		$($(".name_show").find("ul")).html('');
	   		var type = $("#type").val();
	   		loadTeacher(type, teachers, teacherIds);
	   		$('.hide_bd').attr("style", "display: none");
	 		$('.type1').hide();
	   	})
	   	loadItem();
	});
    function imgDel1(thiz) {
    	$.confirm("您确定要删除此照片吗?", "确认删除?", function() {
    		if(courseId == null) attachDel(thiz);
    		else $(thiz).closest("li").remove();
        }, function() {
        });
    }
    function listDel(thiz) {
    	$(thiz).remove();
    }
    function searchPoint(thiz) {
    	var teacherId = $(thiz).attr("data-id");
    	var teacherName = $(thiz).attr("data-name");
    	$('.name_show_box ul').html('');
    	$('.name_show_box').hide();
    	$("#weui_search_input").val(null);
   		$('.name_show').find('ul').append('<li onclick="listDel(this)" class="list-del" data-id="'+teacherId+'" data-name="'+teacherName+'">'+teacherName+'<span class="list-del-vaild"></span></li>');
    }
    function initPage() {
    	$("#courseName").attr("readonly",null);
    	$("#courseDesc").attr("readonly",null);
    	$("#filePicker").show();
    	$("#classAddr").attr("readonly",null);
    	$("#rainAddr").attr("readonly",null);
    	$("#limitNum").attr("readonly",null);
    	$("#teachingObject").attr("readonly",null);
    	$("#teacherConf").show();
    	$("#watchTeacherConf").show();
    	$(".img-del").show();
    }
    function loadMaskTeacher(type) {
    	var teacher,teacherId;
    	if(type == 'classTeachers') {
    		teacher = $("#classTeacher").val();
    		teacherId = $("#classTeacherIds").val();
    	}else if(type == 'watchTeachers') {
    		teacher = $("#watchTeacher").val();
    		teacherId = $("#watchTeacherIds").val();
    	}
    	if(teacher != null && teacherId.length > 0) {
			var teacherIds = teacherId.split(",");
			var teachers = new Array();
			if(teacher != null) {
				teachers = teacher.split(",");
			}
			var teacherHtml = "";
			for(var i in teacherIds) {
				if(teachers[i]) {
					teacherHtml += '<li onclick="listDel(this)" class="list-del" data-id="'+teacherIds[i]+'" data-name="'+teachers[i]+'">'+teachers[i]+'<span class="list-del-vaild"></span></li>';
				}
			}
			$(".name_show ul").html(teacherHtml);
		}
    }
    function loadTeacher(type, teacher, teacherId) {
    	if(type == 'classTeachers') {
    		$("#classTeacher").val(teacher);
    		$("#classTeacherIds").val(teacherId);
    	}else if(type == 'watchTeachers') {
    		$("#watchTeacher").val(teacher);
    		$("#watchTeacherIds").val(teacherId);
    	}
    	if(teacher != null) {
    		teacher = teacher.replace("、",",");
			var teachers = teacher.split(",");
			var teacherIds = new Array();
			if(teacherId != null){
				teacherIds = teacherId.split(",");
			}
			var teacherHtml = "";
			for(var i in teachers) {
				var id = "";
				if(teacherIds.length > i) {
					id = teacherIds[i];
				}
				teacherHtml += "<li><p data-id='"+ teacherId +"'>"+ teachers[i] +"</p></li>";
			}
			$("#" + type).html(teacherHtml);
		}
   }
   
   function examSubmit() {
	   var courseName = emptyToNull($("#courseName").val());
	   if(courseName == null) {
		   $.alert("课程名称不能为空","");
		   return;
	   }
	   var courseDesc = emptyToNull($("#courseDesc").val());
	   if(courseDesc == null) {
		   $.alert("请输入课程描述","");
		   return;
	   }
	   var classTeacher = emptyToNull($("#classTeacher").val());
	   if(classTeacher == null) {
		   $.alert("请选择任课老师","");
		   return;
	   }
	   var classTeacherIds = emptyToNull($("#classTeacherIds").val());
	   var classAddr = emptyToNull($("#classAddr").val());
	   if(classAddr == null) {
		   $.alert("请输入上课地点","");
		   return;
	   }
	   var rainAddr = emptyToNull($("#rainAddr").val());
	   var limitNum = emptyToNull($("#limitNum").val());
	   var teachingObject = emptyToNull($("#teachingObject").val());
	   if(teachingObject == null) {
		   $.alert("请输入授课对象","");
		   return;
	   }
	   var watchTeacher = emptyToNull($("#watchTeacher").val());
	   var watchTeacherIds = emptyToNull($("#watchTeacherIds").val());
	   var attachIds = "";
	   var mainImg = "";
	   var len = $("#img1 li").length;
	   $("#img1 li").each(function(i, v) {
		   if(i==0) mainImg = $(v).attr("data-src")
		   attachIds += $(v).attr("data-id") + ((i+1) < len ? "," : "");
	   })
	   $.ajax({
	   		url: basePath + "/ls/interest/course/addUpdate",
	   		type: 'POST',
	   		dataType : "json",
	   		data: {
	   			id: courseId,
	   			courseName: courseName,
	   			courseDesc: courseDesc,
	   			classTeacher: classTeacher,
	   			classTeacherIds: classTeacherIds,
	   			classAddr: classAddr,
	   			rainAddr: rainAddr,
	   			limitNum: limitNum,
	   			teachingObject: teachingObject,
	   			watchTeacher: watchTeacher,
	   			watchTeacherIds: watchTeacherIds,
	   			attachIds: attachIds,
	   			mainImg: mainImg
	   		},
	   		success: function(data) {
	   			if (data.code == '000') {
	   				$.toast("提交成功");
	   				setTimeout(function() {
	   					window.location.href = basePath + "/ls/interest/course/list?nt=edit&v=" + new Date().getTime();
	   				}, 1000);
	   			}else {
	   				$.toast(data.msg, "cancel");
	   			}
	   		},
	   		error: function(data) {
	   			alert("系统异常,请联系管理员");
	   		}
	   });
   }
   function loadItem() {
	   if(courseId == null) return;
	   $.ajax({
	   		url: basePath + "/ls/interest/course/detail/query",
	   		type: 'POST',
	   		dataType : "json",
	   		data: {
	   			courseId: courseId,
	   		},
	   		success: function(data) {
	   			if(data != null) {
	   				$("#courseName").val(data.courseName);
	   				$("#courseDesc").val(data.courseDesc);
	   				$("#classAddr").val(data.classAddr);
	   				$("#rainAddr").val(data.rainAddr);
	   				$("#limitNum").val(data.limitNum);
	   				$("#teachingObject").val(data.teachingObject);
	   				loadTeacher("classTeachers", data.classTeacher, data.classTeacherIds);
	   				loadTeacher("watchTeachers", data.watchTeacher, data.watchTeacherIds);
	   				if(data.attachList) {
	   					var html = "";
	   					for(var i in data.attachList) {
	   						var itm = data.attachList[i];
	   						html += '<li class="weui_uploader_file" data-id="'+itm.id+'" data-src="'+itm.attachmentUrl+'" style="margin-right:0;margin-bottom:16px;position: relative;"><div class="img-del" onclick="imgDel1(this)"><span class="icon icon-26"></span></div><img onclick="imgClick(this)" src="'+ imgUrl + itm.attachmentUrl +'"/></li>';
	   					}
	   					$("#img1").html(html);
	   					$(".img-del").hide();
	   				}
	   			}
	   		},
	   		error: function(data) {
	   			alert("系统异常,请联系管理员");
	   		}
	   });
   }
   var search = false;
   function queryItem(keyword) {
		if(!/^[\u4E00-\u9FA5]+$/.test(keyword)) return;
		if(search) return;
		search = true;
		$.ajax({
    		url: basePath + "/ls/teacher/manage/keyword",
    		type: 'POST',
    		dataType : "json",
    		data: {
    			teacherName: keyword
    		},
    		success: function(data) {
    			search = false;
    			if (data != null && data.length > 0) {
    				var html = "";
    				for(var i in data) {
    					var itm = data[i];
    					html += "<li onclick='searchPoint(this)' data-id="+itm.id+" data-name="+itm.name+">"+itm.name+"</li>";
    				}
    				$(".name_show_box ul").html(html);
    			}
    		},
    		error: function(data) {
    			alert("系统异常,请联系管理员");
    		}
    	});
	}
   
   document.querySelector('#imgid').onchange = function(e) {
		var files = e.target.files;
		var len = files.length;
		for (var i=0; i < len; i++) {
			lrz(files[i], {
				width:1080
			})
			.then(function (rst) {
				var xhr = new XMLHttpRequest();
	            xhr.open('POST', basePath + "/ls/attchment/upload/lrz");
	            xhr.onload = function () {
	                if (xhr.status === 200) {
	                	var obj = JSON.parse(xhr.response)
	                	$("#img1").append('<li class="weui_uploader_file" data-id="'+obj.data.id+'" data-src="'+obj.data.attachmentUrl+'" style="margin-right:0;margin-bottom:10px;position: relative;"><div class="img-del" onclick="imgDel1(this)"><span class="icon icon-26"></span></div><img onclick="imgClick(this)" src="'+ rst.base64 +'"/></li>')
	                }
	            };
	            xhr.onerror = function () {
	            	alert("上传异常");
	            };
	            xhr.upload.onprogress = function (e) {
	                // 上传进度
	                var percentComplete = ((e.loaded / e.total) || 0) * 100;
	            };
	            // 添加参数
	            rst.formData.append('attachmentName', rst.origin.name);
	            rst.formData.append('attachmentSize', rst.fileLen);
	            rst.formData.append('baseData', rst.base64);
	            rst.formData.append('attachmentType', "image");
	            rst.formData.append('relationType', "interestCourse");
	            // 触发上传
	            xhr.send(rst.formData);
	            return rst;
			})
	        .always(function () {
	            // 不管是成功失败，都会执行
	        });
			;
		}
	}

	//拍照或从手机相册中选图接口
	/* $('#filePicker').on('click', function () {
		wx.chooseImage({
		    count: 9,
		    needResult: 1,
		    sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
		    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
		    success: function (res) {
		   		var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
		   		wxuploadImage(localIds);
		    },
		    fail: function (res) {
		        alterShowMessage("操作提示", JSON.stringify(res), "1", "确定", "", "", "");
		    }
		
		});
	}); */
	function wxuploadImage(localIds) {  
		var localId = localIds.pop();
		wx.uploadImage({  
		    localId: localId, // 需要上传的图片的本地ID，由chooseImage接口获得  
		    isShowProgressTips: 1, // 默认为1，显示进度提示  
		    success: function (res) {  
		        mediaId = res.serverId; // 返回图片的服务器端ID
		        wechatMediaDownload(mediaId);
		        if(localIds.length > 0){
		        	wxuploadImage(localIds);
		        }
		    },  
		    fail: function (error) {  
		        alert(Json.stringify(error));  
		    }  
		});
	}  
	function wechatMediaDownload(mediaId) {
		var params = {};
		params.mediaId = mediaId;
		params.attachmentType = "image";
		params.relationType = "interestCourse";
		$.ajax({
			url : basePath + "/ls/attchment/upload/wx",
			type : "post",
			data : params,
			dataType : "json",
			async : false,
			success : function(data) {
				if(data.code != '000') {
					$.toast(data.msg, "cancel");
				}else {
					$('#img1').append('<li class="weui_uploader_file" data-id="'+data.data.id+'" data-src="'+data.data.attachmentUrl+'" style="margin-right:0;margin-bottom:16px;position: relative;"><div class="img-del" onclick="imgDel1(this)"><span class="icon icon-26"></span></div><img onclick="imgClick(this)" src="'+ imgUrl + data.data.attachmentUrl +'"/></li>'); 
				}
			}, error:function(){
				alert("上传异常");
				}
		});
	}
</script>
</html>